import {createRouter, createWebHistory} from 'vue-router'
import loginRequest from '@/api/login.js';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/",
            component: () => import("@/views/login.vue")
        }, {
            path: "/home",
            component: () => import("@/views/home.vue"),
            children: [
                {
                    path:"",
                    alias:"welcome",
                    component:()=>import("@/views/welcome.vue")
                },
                {
                    path: "sys/dict",
                    component: () => import("@/views/dict/dict-list.vue")
                },
                {
                    path: "machine/type",
                    component: () => import("@/views/machineType/machineTypeList.vue")
                },
                {
                    path: "machine/ledger",
                    component: () => import("@/views/machineType/machineLedger.vue")
                },
                {
                    path: "machine/maintainItems",
                    component: () => import("@/views/machineType/machineMaintainItems.vue")
                },
                {
                    path: "machine/maintainPlan",
                    component: () => import("@/views/machineType/machineMaintainPlan.vue")
                },
                {
                    path: "tools/types",
                    component: () => import("@/views/tools/toolType.vue")
                },
                {
                    path:"tools/ledger",
                    component:()=>import("@/views/tools/toolTypeLedger.vue")
                },
                {
                    path:"store/setting",
                    component:()=>import("@/views/store/storeSetting.vue")
                },
                {
                    path:"store/stock",
                    component:()=>import("@/views/store/stock/storeStock.vue")
                }
            ]
        }
    ]
})

// 添加路由守卫，进行登录判断
router.beforeEach(async (to, from) => {
    console.log("to:" + to.path);
    console.log("from:" + from.path);
    if (to.path != '/') {
        // 不是访问登录页面,访问其他页面，这时就需要判断是否登录。
        // 判断策略就是将token发送到服务器端进行判断。  但是token在哪？
        // 获取token
        let token = localStorage.getItem("token")
        // 发送请求进行校验
        let result = await loginRequest.checkLogin(token);
        console.log(result)
        if (result.code != '200') {
            return "/";
        } else {
            return true;
        }
    } else {
        // 返回 false 以取消导航
        return true;
    }
})
export default router
